# load packages

pacman::p_load(tidyverse, scales)

### figure A.7 (priming individuals on pools and AfD vote intention) ----

# load data
pools <- read_rds("data/survey.rds")

# create dummies for treatment group and high immigrant share
pools_split <- pools %>%
    mutate(Group = ifelse(Group == "Treatment", 1, 0),
           imm_share = ifelse(imm_share == "High", 1, 0))

# split data by immigrant share
imm_low <- pools_split %>%
    filter(imm_share == 0)
imm_high <- pools_split %>%
    filter(imm_share == 1)

# perform t-test
t.test(imm_low$vote_afd[imm_low$Group == 0], imm_low$vote_afd[imm_low$Group == 1])
t.test(imm_high$vote_afd[imm_high$Group == 0], imm_high$vote_afd[imm_high$Group == 1])

# calculate confidence intervals for plot
experiment <- pools %>%
    filter(!is.na(imm_share)) %>%
    group_by(imm_share, Group) %>%
    summarise(
        mean_outcome = mean(vote_afd, na.rm = TRUE),
        ci_lower = mean_outcome - qt(0.975, df = n() - 1) * sd(vote_afd, na.rm = TRUE) / sqrt(n()),
        ci_upper = mean_outcome + qt(0.975, df = n() - 1) * sd(vote_afd, na.rm = TRUE) / sqrt(n())
    ) %>%
    ungroup()

# create plot
ggplot(experiment, aes(x = factor(imm_share), y = mean_outcome, color = Group, group = Group)) +
    geom_point(position = position_dodge(width = 0.3), size = 3) +
    geom_errorbar(aes(ymin = ci_lower, ymax = ci_upper), width = 0.1, position = position_dodge(width = 0.3)) +
    labs(x = "Second Variable (split_var)", y = "Mean Outcome", color = "Group") +
    theme_bw() +
    labs(title=element_blank(), x="Immigrant Share", y="Share AfD Vote") +
    scale_color_manual(values = c("darkgrey", "black")) +
    theme(
        legend.title = element_blank(), 
        legend.position = "bottom",
        axis.title.y = element_text(size = 16),
        axis.title.x = element_text(size = 16),
        title = element_blank(),
        panel.grid.minor = element_blank(),
        panel.grid.major = element_blank(),
        panel.border = element_rect(color = "black", fill = NA, linewidth = 1),
        axis.ticks = element_line(color = "black"),
        axis.ticks.length = unit(0.2, "cm"),
        panel.background = element_rect(fill = "white", colour = "white")) +
    theme(text = element_text(size = 16)) +
    annotate("text", x=1, y=.242, label= "p=.03**") +
    geom_segment(aes(x = .9, y = .235, xend = 1.1, yend = .235), lwd=.3) +
    geom_segment(aes(x = .9, y = .235, xend = .9, yend = .23), lwd=.3) +
    geom_segment(aes(x = 1.1, y = .235, xend = 1.1, yend = .23), lwd=.3) +
    annotate("text", x=2, y=.242, label= "p=.35") +
    geom_segment(aes(x = 1.9, y = .235, xend = 2.1, yend = .235), lwd=.3) +
    geom_segment(aes(x = 1.9, y = .235, xend = 1.9, yend = .23), lwd=.3) +
    geom_segment(aes(x = 2.1, y = .235, xend = 2.1, yend = .23), lwd=.3) +
    ylim(c(.1,.245))

# clean
rm(list = ls())